package com.soyorin.order.controller;

import com.soyorin.order.entity.Order;
import com.soyorin.order.service.OrderService;
import org.springframework.http.ResponseEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService baseService;

    // 添加公共的 setter 方法以便于测试
    public void setBaseService(OrderService baseService) {
        this.baseService = baseService;
    }

    // 标准接口一: select-one
    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Order> selectById(@PathVariable Long id) {
        Order Order = baseService.getById(id);
        if(Order != null) { // return1: 成功查询到数据
            return ResponseEntity.status(200).body(Order);
        } else { // return2: 未找到对应数据
            return ResponseEntity.status(404).body(null);
        }
    }

    // 标准接口二: select-all
    @GetMapping
    @ResponseBody
    public PageInfo<Order> selectAll(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> list = baseService.list();
        return new PageInfo<>(list);
    }

    // 标准接口三: insert
    @PostMapping
    @ResponseBody
    public ResponseEntity<Order> insert(@RequestBody Order Order) {
        boolean result = baseService.save(Order);
        if(result) { // return1: 成功插入数据
            return ResponseEntity.status(200).body(Order);
        } else { // return2: 插入数据失败
            return ResponseEntity.status(500).body(null);
        }
    }

    // 标准接口四: delete
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Order> delete(@PathVariable Long id) {
        Order Order = baseService.getById(id);
        if(Order != null) {
            boolean result = baseService.removeById(id);
            if(result) { // return1: 成功删除数据
                return ResponseEntity.status(200).body(Order);
            } else { // return2: 删除数据失败
                return ResponseEntity.status(500).body(Order);
            }
        } else { // return3: 未找到对应数据
            return ResponseEntity.status(404).body(null);
        }
    }

    // 标准接口五: update
    @PutMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Order> update(
            @PathVariable Long id,
            @RequestBody Order Order) {
        Order.setId(id);
        boolean result = baseService.updateById(Order);
        Order updateOrder = baseService.getById(Order.getId());
        if(result && updateOrder != null) { // return1: 成功更新数据
            return ResponseEntity.status(200).body(updateOrder);
        } else { // return2: 更新数据失败
            return ResponseEntity.status(500).body(Order);
        }
    }

    // 标准接口六: select-eq
    @PostMapping("/select-eq")
    @ResponseBody
    public ResponseEntity<List<Order>> selectEq(
            @RequestBody Map<String,Object> conditions) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        for(Map.Entry<String, Object> entry : conditions.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            wrapper.eq(key, value);
        }
        List<Order> list = baseService.list(wrapper);
        if(list != null && !list.isEmpty()) { // return1: 成功查询到数据
            return ResponseEntity.status(200).body(list);
        } else { // return2: 未找到对应数据
            return ResponseEntity.status(404).body(null);
        }
    }
    
    // 扩展接口: 根据用户ID查询订单
    @GetMapping("/user/{userId}")
    @ResponseBody
    public PageInfo<Order> selectByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("rela_c_user_id", userId);
        wrapper.orderByDesc("create_time");
        List<Order> list = baseService.list(wrapper);
        return new PageInfo<>(list);
    }
    
    // 扩展接口: 根据商店ID查询订单
    @GetMapping("/shop/{shopId}")
    @ResponseBody
    public PageInfo<Order> selectByShopId(
            @PathVariable Long shopId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("rela_b_user_id", shopId); // 假设商店ID存储在rela_b_user_id字段
        wrapper.orderByDesc("create_time");
        List<Order> list = baseService.list(wrapper);
        return new PageInfo<>(list);
    }
    
    // 扩展接口: 更新订单状态
    @PutMapping("/{orderId}/status")
    @ResponseBody
    public ResponseEntity<Order> updateStatus(
            @PathVariable Long orderId,
            @RequestBody Map<String, String> statusData) {
        try {
            Order order = baseService.getById(orderId);
            if (order == null) {
                return ResponseEntity.status(404).body(null);
            }
            
            String status = statusData.get("status");
            if (status == null || status.trim().isEmpty()) {
                return ResponseEntity.status(400).body(null);
            }
            
            boolean statusHandled = false; // 新增标志位，标记状态是否被有效处理
            // 根据状态更新相应的标志位
            switch (status.toLowerCase()) {
                case "confirmed":
                    order.setBDefine(Boolean.TRUE); // 使用Boolean.TRUE
                    statusHandled = true;
                    break;
                case "preparing":
                    order.setCooked(Boolean.TRUE); // 使用Boolean.TRUE
                    statusHandled = true;
                    break;
                case "delivering":
                    order.setArriveB(Boolean.TRUE); // 使用Boolean.TRUE
                    statusHandled = true;
                    break;
                case "completed":
                    order.setArriveC(Boolean.TRUE); // 使用Boolean.TRUE
                    statusHandled = true;
                    break;
                default:
                    // 其他状态暂不处理，直接返回400 Bad Request
                    return ResponseEntity.status(400).body(null); // 修改这里
            }

            // 只有当状态被有效处理时才尝试更新
            if (statusHandled) {
                boolean result = baseService.updateById(order);
                if (result) {
                    return ResponseEntity.status(200).body(order);
                } else {
                    return ResponseEntity.status(500).body(null);
                }
            } else {
                // 如果没有状态被处理，但也没有进入default，理论上不会走到这里，
                // 但作为兜底，也返回400
                return ResponseEntity.status(400).body(null);
            }

        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }
    
    // 扩展接口: 获取订单统计数据
    @GetMapping("/stats")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getOrderStats(
            @RequestParam(required = false) Long shopId,
            @RequestParam(required = false) String dateRange) {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            if (shopId != null) {
                wrapper.eq("rela_b_user_id", shopId);
            }
            
            // 获取订单列表进行统计
            List<Order> orders = baseService.list(wrapper);
            
            // 计算统计数据
            int totalOrders = orders.size();
            double totalRevenue = 0;
            int newCustomers = 0;
            double avgRating = 4.5; // 默认评分
            
            for (Order order : orders) {
                // 这里需要根据实际的订单金额字段进行计算
                // 由于Order实体类字段不明确，使用模拟数据
                totalRevenue += Math.random() * 200 + 50; // 模拟订单金额
            }
            
            // 模拟月度数据
            double[] monthlyRevenue = new double[7];
            int[] monthlyOrders = new int[7];
            for (int i = 0; i < 7; i++) {
                monthlyRevenue[i] = Math.random() * 3000 + 1000;
                monthlyOrders[i] = (int)(Math.random() * 50 + 20);
            }
            
            stats.put("totalRevenue", (int)totalRevenue);
            stats.put("totalOrders", totalOrders);
            stats.put("newCustomers", Math.max(1, totalOrders / 5)); // 模拟新客户数
            stats.put("avgRating", avgRating);
            stats.put("monthlyRevenue", monthlyRevenue);
            stats.put("monthlyOrders", monthlyOrders);
            
            return ResponseEntity.status(200).body(stats);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }
}